package com.jz.community.basecomm.task;

import android.app.Activity;

import com.jz.community.basecomm.bean.LoginBaseInfo;
import com.jz.community.basecomm.bean.UserInfo;
import com.jz.community.basecomm.constant.Constant;
import com.jz.community.basecomm.net.OkHttpUtil;
import com.jz.community.basecomm.reflection.refreshtoken.RefreshTokenActionReflectUtils;
import com.jz.community.basecomm.utils.BaseSpUtils;
import com.jz.community.basecomm.utils.JsonUtils;
import com.jz.community.basecomm.utils.Preconditions;
import com.jz.community.commview.view.widget.ProgressDialogManager;

import java.util.HashMap;

import cn.jpush.android.api.JPushInterface;

/**
 * Created by Tony.Fan on 2018/5/8 16:50
 */
public class GetUserInfoTask extends RxTask<String, Integer, UserInfo> {
    private Activity activity;
    private ITaskCallbackListener taskListener;

    public GetUserInfoTask(Activity activity,
                           ITaskCallbackListener taskListener) {
        super(activity);
        this.activity = activity;
        this.taskListener = taskListener;
    }

    @Override
    protected UserInfo doInBackground(String... params) {
        UserInfo info = null;

        // 执行请求
        String result = OkHttpUtil.get(Constant.USER_MSG_URL, getParam());

        if (!Preconditions.isNullOrEmpty(result)) {
            info = JsonUtils.parseObject(result, UserInfo.class);
            if (!Preconditions.isNullOrEmpty(info)) {
                saveUserInfo(info);
            }
        }
        return info;
    }

    @Override
    protected void onPostExecute(UserInfo result) {
        // 执行结果回调函数
        taskListener.doTaskComplete(result);
        super.onPostExecute(result);
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected void onCancelled() {
        super.onCancelled();
    }

    private HashMap<String, Object> getParam() {
        HashMap<String, Object> params = new HashMap<>();
        params.put("access_token", BaseSpUtils.getInstance().getAccess_token(activity));
        return params;
    }

    /**
     * @param userInfo
     */
    private void saveUserInfo(UserInfo userInfo) {
        LoginBaseInfo loginBaseInfo = new LoginBaseInfo();
        loginBaseInfo.setMobi(userInfo.getPhone());
        loginBaseInfo.setName(userInfo.getName());
        loginBaseInfo.setInitPwd(userInfo.isInitPwd());
        BaseSpUtils.getInstance().setUserBaseInfo(activity, loginBaseInfo);
    }
}
